<template>
  <view class="giftbook-info" :class="{'expanded': isExpanded}">
    <!-- 标题与展开按钮 -->
    <view class="info-header">
      <!-- 标题 - 点击编辑 -->
      <view class="title-wrapper" @tap="startEdit('title')">
        <view v-if="!isEditingField.title" class="title">
          {{ giftBook?.title || '未命名礼簿' }}
          <text class="edit-icon">✎</text>
        </view>
        <input 
          v-else 
          class="title-input" 
          v-model="editingData.title" 
          focus 
          @blur="saveEdit('title')"
          @confirm="saveEdit('title')"
        />
      </view>
      
      <!-- 展开/收起按钮 -->
      <view class="expand-btn" @tap="toggleExpand">
        <text class="expand-text">{{ isExpanded ? '收起' : '展开' }}</text>
        <text class="expand-icon" :class="{'expanded': isExpanded}">
          {{ isExpanded ? '↑' : '↓' }}
        </text>
      </view>
    </view>

    <!-- 总金额：始终显示 -->
    <view class="total">
      <view class="total-item received">
        <text class="label">收入</text>
        <text class="amount income">¥{{ formatAmount(giftBook?.totalReceived || 0) }}</text>
      </view>
      <view class="total-item given">
        <text class="label">支出</text>
        <text class="amount outcome">¥{{ formatAmount(giftBook?.totalGiven || 0) }}</text>
      </view>
    </view>

    <!-- 详细信息：展开时才显示 -->
    <view class="details-content" v-if="isExpanded">
      <view class="meta">
        <text class="type">{{ getTypeLabel(giftBook?.type) }}</text>
          
        <!-- 日期 - 点击编辑 -->
        <view class="date-wrapper" @tap="startEdit('date')">
          <text v-if="!isEditingField.date" class="date">
            {{ formatDate(giftBook?.date) }}
            <text class="edit-icon">✎</text>
          </text>
          <picker 
            v-else 
            mode="date" 
            :value="editingData.date" 
            @change="handleDateChange"
          >
            <view class="date-picker">
              {{ formatDate(editingData.date) }}
            </view>
          </picker>
        </view>
      </view>

      <!-- 地点 - 点击编辑 -->
      <view class="location" v-if="giftBook?.location || isEditingField.location" @tap="startEdit('location')">
        <text class="iconfont icon-location"></text>
        <text v-if="!isEditingField.location">{{ giftBook?.location }} <text class="edit-icon">✎</text></text>
        <input 
          v-else 
          class="location-input" 
          v-model="editingData.location" 
          focus 
          placeholder="请输入地点"
          @blur="saveEdit('location')"
          @confirm="saveEdit('location')"
        />
      </view>
      <view class="location add-location" v-else @tap="startEdit('location')">
        <text class="iconfont icon-location"></text>
        <text>添加地点</text>
      </view>

      <!-- 描述 - 点击编辑 -->
      <view class="description-wrapper" @tap="startEdit('description')">
        <view v-if="!isEditingField.description && giftBook?.description" class="description">
          {{ giftBook?.description }}
          <text class="edit-icon">✎</text>
        </view>
        <view v-else-if="!isEditingField.description" class="description empty-description">
          添加描述
          <text class="edit-icon">✎</text>
        </view>
        <textarea 
          v-else 
          class="description-input" 
          v-model="editingData.description" 
          focus 
          placeholder="请输入描述"
          @blur="saveEdit('description')"
        />
      </view>
    </view>
  </view>
</template>

<script setup lang="ts">
import { ref, computed } from 'vue';
import { useGiftBookStore } from '@/store/modules/giftbook';
import { GiftBookType, GiftBook } from '@/types/giftbook';

const props = defineProps({
  giftBook: {
    type: Object as () => GiftBook,
    required: true
  },
  giftBookId: {
    type: String,
    required: true
  }
});

const emit = defineEmits(['update:giftBook']);

const giftBookStore = useGiftBookStore();

// 是否展开状态
const isExpanded = ref(false);

// 字段编辑状态
const isEditingField = ref({
  title: false,
  date: false,
  location: false,
  description: false
});

// 编辑中的数据
const editingData = ref({
  title: '',
  date: '',
  location: '',
  description: ''
});

// 切换展开状态
const toggleExpand = () => {
  isExpanded.value = !isExpanded.value;
};

// 开始编辑字段
const startEdit = (field: 'title' | 'date' | 'location' | 'description') => {
  // 重置所有编辑状态
  Object.keys(isEditingField.value).forEach(key => {
    isEditingField.value[key as keyof typeof isEditingField.value] = false;
  });
  
  // 设置当前编辑字段状态为true
  isEditingField.value[field] = true;
  
  // 初始化编辑数据
  if (props.giftBook) {
    switch(field) {
      case 'title':
        editingData.value.title = props.giftBook.title || '';
        break;
      case 'date':
        editingData.value.date = props.giftBook.date || '';
        break;
      case 'location':
        editingData.value.location = props.giftBook.location || '';
        break;
      case 'description':
        editingData.value.description = props.giftBook.description || '';
        break;
    }
  }
};

// 添加日期变更处理函数
const handleDateChange = (e: any) => {
  editingData.value.date = e.detail.value;
  saveEdit('date');
};

// 保存编辑
const saveEdit = async (field: 'title' | 'date' | 'location' | 'description') => {
  if (!props.giftBook) return;
  
  try {
    // 创建更新后的礼簿对象
    const updatedGiftBook = { ...props.giftBook };
    
    // 更新对应字段
    switch(field) {
      case 'title':
        updatedGiftBook.title = editingData.value.title;
        break;
      case 'date':
        updatedGiftBook.date = editingData.value.date;
        break;
      case 'location':
        updatedGiftBook.location = editingData.value.location;
        break;
      case 'description':
        updatedGiftBook.description = editingData.value.description;
        break;
    }
    
    // 更新礼簿数据
    giftBookStore.updateGiftBook(updatedGiftBook);
    
    // 直接更新本地的当前礼簿引用，确保视图立即更新
    // 由于Vue 3的响应式特性，这个更新会立即反映在UI上
    giftBookStore.setCurrentGiftBook(updatedGiftBook);
    
    // 通知父组件数据已更新
    emit('update:giftBook', updatedGiftBook);
    
    // 显示保存成功提示
    uni.showToast({
      title: '保存成功',
      icon: 'success',
      duration: 1500
    });
    
    // 重置编辑状态
    isEditingField.value[field] = false;
  } catch (error) {
    console.error('保存礼簿信息失败:', error);
    uni.showToast({
      title: '保存失败',
      icon: 'error',
      duration: 1500
    });
  }
};

// 获取类型标签
const getTypeLabel = (type: string) => {
  const typeMap: Record<string, string> = {
    wedding: '婚礼',
    birthday: '生日',
    funeral: '丧事',
    graduation: '升学',
    business: '商务',
    housewarming: '乔迁',
    fullmoon: '满月',
    other: '其他',
  };
  return typeMap[type] || '其他';
};

// 格式化日期
const formatDate = (date: string) => {
  if (!date) return 'NaN-NaN-NaN';
  return date;
};

// 格式化金额，大数字使用简写，整数不显示小数部分
const formatAmount = (amount: number) => {
  if (amount === undefined || amount === null) return '0';
  
  // 对大金额进行简化处理
  if (amount >= 100000000) { // 亿
    const value = amount / 100000000;
    return (Number.isInteger(value) ? value.toString() : value.toFixed(2)) + '亿';
  } else if (amount >= 10000) { // 万
    const value = amount / 10000;
    return (Number.isInteger(value) ? value.toString() : value.toFixed(2)) + '万';
  }
  
  // 整数金额不显示小数点后的零
  return Number.isInteger(amount) ? amount.toString() : amount.toFixed(2);
};
</script>

<style lang="scss">
.giftbook-info {
  background-color: #fff;
  border-radius: 12rpx;
  padding: 20rpx;
  margin-bottom: 16rpx;
  box-shadow: 0 2rpx 8rpx rgba(0, 0, 0, 0.05);
  position: relative;
  overflow: hidden;
  transition: all 0.3s ease;
  
  &::before {
    content: '';
    position: absolute;
    top: 0;
    left: 0;
    width: 6rpx;
    height: 100%;
    background-color: var(--primary-color);
  }

  .info-header {
    display: flex;
    justify-content: space-between;
    align-items: center;
    margin-bottom: 12rpx;
  }

  .title-wrapper {
    display: flex;
    align-items: center;
    position: relative;
    padding: 2rpx 0;
    flex: 1;

    .title {
      font-size: 36rpx;
      font-weight: bold;
      color: #333;
      margin-right: 6rpx;
      line-height: 1.2;
    }

    .edit-icon {
      font-size: 22rpx;
      color: #999;
      margin-left: 6rpx;
      opacity: 0;
      transition: opacity 0.2s;
    }
    
    &:hover, &:active {
      .edit-icon {
        opacity: 1;
      }
    }
  }

  .expand-btn {
    display: flex;
    align-items: center;
    padding: 8rpx 12rpx;
    border-radius: 4rpx;
    background-color: #f9f9f9;
    
    .expand-text {
      font-size: 22rpx;
      color: #666;
      margin-right: 4rpx;
    }
    
    .expand-icon {
      font-size: 22rpx;
      color: #666;
      transition: transform 0.3s;
      
      &.expanded {
        transform: rotate(180deg);
      }
    }
  }

  .total {
    font-size: 24rpx;
    color: #333;
    margin-top: 10rpx;
    display: flex;
    align-items: center;
    justify-content: space-between;

    .total-item {
      display: flex;
      flex-direction: column;
      align-items: flex-start;
      padding: 8rpx 16rpx;
      background-color: #f9f9f9;
      border-radius: 8rpx;
      flex: 1;
      
      &.received {
        margin-right: 12rpx;
        background-color: rgba(24, 144, 255, 0.05);
      }
      
      &.given {
        background-color: rgba(255, 82, 82, 0.05);
      }
    }

    .label {
      font-weight: 500;
      font-size: 22rpx;
      color: #666;
      margin-bottom: 4rpx;
    }

    .amount {
      font-weight: bold;
      font-size: 32rpx;
      line-height: 1.2;
      
      &.income {
        color: #1890ff;
      }
      
      &.outcome {
        color: #ff5252;
      }
    }
  }

  .details-content {
    margin-top: 16rpx;
    padding-top: 16rpx;
    border-top: 1px dashed #eee;
    animation: fadeIn 0.3s ease;
    
    @keyframes fadeIn {
      from { opacity: 0; }
      to { opacity: 1; }
    }
  }
  
  &.expanded {
    .total {
      padding-bottom: 12rpx;
    }
  }
}

.meta {
  display: flex;
  align-items: center;
  flex-wrap: wrap;
  margin-bottom: 12rpx;

  .type {
    font-size: 22rpx;
    color: var(--primary-color);
    background-color: var(--primary-light-color);
    padding: 4rpx 12rpx;
    border-radius: 20rpx;
    margin-right: 16rpx;
    margin-bottom: 6rpx;
  }

  .date-wrapper {
    display: flex;
    align-items: center;
    margin-right: 16rpx;
    margin-bottom: 6rpx;
    position: relative;
    padding: 4rpx 6rpx;
    border-radius: 4rpx;
    transition: background-color 0.2s;
    
    &:hover, &:active {
      background-color: rgba(0, 0, 0, 0.05);
      
      .edit-icon {
        opacity: 1;
      }
    }

    .date {
      font-size: 24rpx;
      color: #666;
      margin-right: 6rpx;
      position: relative;
      
      &::before {
        content: '';
        display: inline-block;
        width: 6rpx;
        height: 6rpx;
        border-radius: 50%;
        background-color: #999;
        margin-right: 8rpx;
      }
    }

    .edit-icon {
      font-size: 22rpx;
      color: #999;
      opacity: 0;
      transition: opacity 0.2s;
    }
  }

  .date-picker {
    font-size: 26rpx;
    color: #333;
    padding: 10rpx 20rpx;
    background-color: #f8f8f8;
    border-radius: 8rpx;
    border: 2rpx solid #1890ff;
    text-align: center;
  }
}

.location {
  display: flex;
  align-items: center;
  font-size: 24rpx;
  color: #666;
  margin-bottom: 12rpx;
  padding: 6rpx 8rpx;
  border-radius: 6rpx;
  transition: background-color 0.2s;
  
  &:hover, &:active {
    background-color: rgba(0, 0, 0, 0.05);
    
    .edit-icon {
      opacity: 1;
    }
  }

  .iconfont {
    color: #ff9800;
    margin-right: 8rpx;
    font-size: 28rpx;
  }
  
  .edit-icon {
    font-size: 22rpx;
    color: #999;
    margin-left: 6rpx;
    opacity: 0;
    transition: opacity 0.2s;
  }
}

.location-input {
  width: 100%;
  height: 80rpx;
  line-height: 80rpx;
  padding: 0 24rpx;
  font-size: 28rpx;
  color: #333;
  background-color: #f8f8f8;
  border-radius: 8rpx;
  box-sizing: border-box;
  border: 2rpx solid #1890ff;
}

.location.add-location {
  display: flex;
  align-items: center;
  justify-content: center;
  font-size: 28rpx;
  color: #999;
  padding: 16rpx 0;
  background-color: #f8f8f8;
  border-radius: 8rpx;
  border: 1rpx dashed #ddd;
  cursor: pointer;
  transition: all 0.3s;
  
  &:hover {
    background-color: #f0f0f0;
    color: #666;
  }

  .iconfont {
    margin-right: 10rpx;
    font-size: 32rpx;
  }
}

.description-wrapper {
  margin-bottom: 12rpx;
  border-radius: 6rpx;
  transition: background-color 0.2s;
  
  &:hover, &:active {
    background-color: rgba(0, 0, 0, 0.02);
    
    .edit-icon {
      opacity: 1;
    }
  }
}

.description {
  font-size: 24rpx;
  color: #666;
  line-height: 1.4;
  padding: 12rpx;
  background-color: #f9f9f9;
  border-radius: 6rpx;
  border-left: 3rpx solid #ddd;
  position: relative;

  .edit-icon {
    font-size: 22rpx;
    color: #999;
    position: absolute;
    right: 12rpx;
    top: 12rpx;
    opacity: 0;
    transition: opacity 0.2s;
  }
}

.empty-description {
  font-size: 24rpx;
  color: #999;
  padding: 12rpx;
  background-color: #f9f9f9;
  border-radius: 6rpx;
  border-left: 3rpx solid #ddd;
  text-align: center;

  .edit-icon {
    font-size: 22rpx;
    color: #999;
    margin-left: 6rpx;
    opacity: 0;
    transition: opacity 0.2s;
  }
}

.description-input {
  width: 100%;
  height: 160rpx;
  line-height: 1.5;
  padding: 16rpx 24rpx;
  font-size: 28rpx;
  color: #333;
  background-color: #f8f8f8;
  border-radius: 8rpx;
  border: 2rpx solid #1890ff;
}

.title-input {
  width: 100%;
  height: 80rpx;
  line-height: 80rpx;
  padding: 0 24rpx;
  font-size: 36rpx;
  font-weight: bold;
  color: #333;
  background-color: #f8f8f8;
  border-radius: 8rpx;
  box-sizing: border-box;
  border: 2rpx solid #1890ff;
}
</style> 